<template>
  <div class="crane" :style="{ color: dark ? '#fff' : '#000' }">
    <div class="craneInfo row">
      <div class="ch1">
        <div class="example row justify-between q-px-lg" style="color: #dd9d4b">
          <div style="color: #eacca5">当前X:</div>

          <div style="color: #eacca5">{{ craneData.xAct }} mm</div>
        </div>
        <div class="example row justify-between q-px-lg" style="color: #dd9d4b">
          <div style="color: #eacca5">当前Y:</div>

          <div style="color: #eacca5">{{ craneData.yAct }} mm</div>
        </div>

        <div class="example row justify-between q-px-lg q-mt-sm" style="color: #dd9d4b">
          <div style="color: #eacca5">X偏差:</div>

          <div style="color: #eacca5">{{ orderStatus ? xDeviation : '' }} mm</div>
        </div>
        <div class="example row justify-between q-px-lg" style="color: #dd9d4b">
          <div style="color: #eacca5">Y偏差:</div>

          <div style="color: #eacca5">{{ orderStatus ? yDeviation : '' }} mm</div>
        </div>
        <!-- <div class=""><span>当前库位:</span>{{ currentPosition }}</div> -->
      </div>

      <div class="column justify-between ch3">
        <div class="clock">
          <!-- :style="{ transform: `translate(-50%, -100%) rotate(${angle}deg)` }" -->
          <div v-if="angle" class="hand" :style="{ transform: angle }"></div>
        </div>
      </div>
    </div>
    <div class="row craneIocn">
      <div class="network" v-if="craneData.network">
        <div class="child-element">网络正常</div>
      </div>

      <div class="networkA" v-else>
        <div class="child-element">网络异常</div>
      </div>
      <div :class="{ empty_is: craneData.isEmpty != '1', empty: craneData.isEmpty == '1' }">
        <div class="child-element">{{ craneData.isEmpty != '1' ? '无载荷' : '有载荷' }}</div>
      </div>
      <div :class="{ lifting: operateModeM == '3', lifting_2: operateModeM == '2' }" @click="handleClick('指令起吊')">
        <div class="child-element">强制起吊</div>
      </div>

      <!-- <div class="lifting_2" @click="handleClick('指令起吊')">
        <div class="child-element">强制起吊</div>
      </div> -->

      <div :class="{ unload: operateModeM == '3', unload_2: operateModeM == '2' }" @click="handleClick('指令卸下')">
        <div class="child-element">强制卸下</div>
      </div>
      <div class="sift">
        <q-menu style="background-color: #2c2333; opacity: 0.9" @show="onShow">
          <div class="orderMenu q-gutter-y-md">
            <div class="left row justify-between" v-for="v in sift" :key="v.sift">
              <div class="hexagon">{{ v.Group }}</div>
              <div
                class="orderTpye"
                v-for="o in v.OrderType.split(',')"
                :key="o.id"
                v-close-popup
                @click="orderTypeClick(o)"
              >
                {{ orderTypeName ? orderTypeName[o] : '' }}
              </div>
            </div>
            <!-- <div ref="container"></div> -->
          </div>
        </q-menu>
      </div>
      <div class="setUp" @click="onModeChange"></div>
    </div>
  </div>
</template>

<script lang="ts">
import G6 from '@antv/g6';
import { storeToRefs } from 'pinia';
import { api } from 'src/boot/api';
import { emitter } from 'src/emitter';
import { PropType, computed, defineComponent, onMounted, ref } from 'vue';
import { CraneProps } from '../main/models';
import { useTerminalStore } from '../store';

class Coordinate {
  x: number;
  y: number;

  constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
  }
}

export default defineComponent({
  name: 'terminal-crane-info',

  props: {
    dark: {
      type: Boolean,
      required: true,
    },
    craneData: {
      type: Object as PropType<CraneProps>,
      required: true,
    },

    operateMode: {
      type: String,
      required: true,
    },

    orderSift: {
      type: Object as PropType<any[]>,
      required: true,
    },
  },

  setup(props) {
    // const data = {
    //   // 点集
    //   nodes: [
    //     {
    //       id: 'node1', // String，该节点存在则必须，节点的唯一标识
    //       label: '全部',
    //       type: 'rect',
    //       x: 100, // Number，可选，节点位置的 x 值
    //       y: 200, // Number，可选，节点位置的 y 值
    //       size: 40,
    //     },
    //     {
    //       id: 'node2', // String，该节点存在则必须，节点的唯一标识
    //       x: 300, // Number，可选，节点位置的 x 值
    //       y: 200, // Number，可选，节点位置的 y 值
    //     },
    //   ],
    //   // 边集
    //   edges: [
    //     {
    //       source: 'node1', // String，必须，起始点 id
    //       target: 'node2', // String，必须，目标点 id
    //     },
    //   ],
    // };

    const store = useTerminalStore();
    const { orderStatus, posx, posy, orderTypeName } = storeToRefs(store);

    const container = ref<HTMLDivElement | null>(null);

    const sift = computed(() => {
      return props.orderSift;
      // return props.orderSift.filter(v => v.CraneNo == '01');
    });

    const operateModeM = computed(() => {
      return props.operateMode;
    });

    const xDeviation = computed(() => {
      return Number(props.craneData.xAct) - Number(posx.value);
    });

    const yDeviation = computed(() => {
      return Number(props.craneData.yAct) - Number(posy.value);
    });

    function calculateAngle(x1: number, y1: number, x2: number, y2: number): string {
      // 计算x差值和y差值
      const deltaX = x1 - x2;
      const deltaY = y1 - y2;

      // if (props.craneData.isEmpty !== '1') {
      //   deltaX = x2 - x1;
      //   deltaY = y2 - y1;
      // } else {
      //   deltaX = x1 - x2;
      //   deltaY = y1 - y2;
      // }

      // 使用反正切函数计算角度的弧度值
      // const radian = Math.atan2(deltaY, deltaX);

      // 转换为角度值
      // const angle = radian * (180 / Math.PI);
      // if (y2 < y1) {
      //   return -angle;
      // } else {
      //   return angle;
      // }

      if (!orderStatus.value) {
        return '';
      }

      if (deltaX > -1000 && deltaX < 1000) {
        if (deltaY > 1000) {
          return 'translate(-50%, -100%) rotate(180deg)';
        } else if (deltaY < -1000) {
          return 'translate(-50%, -100%) rotate(0deg)';
        } else {
          return '';
        }
      } else if (deltaX < -1000) {
        if (deltaY > -1000 && deltaY < 1000) {
          return 'translate(-50%, -100%) rotate(90deg)';
        } else if (deltaY < -1000) {
          return 'translate(-50%, -100%) rotate(45deg)';
        } else {
          return 'translate(-50%, -100%) rotate(135deg)';
        }
      } else {
        if (deltaY > -1000 && deltaY < 1000) {
          return 'translate(-50%, -100%) rotate(-90deg)';
        } else if (deltaY < -1000) {
          return 'translate(-50%, -100%) rotate(-45deg)';
        } else {
          return 'translate(-50%, -100%) rotate(-135deg)';
        }
      }
    }

    const angle = computed(() => {
      return calculateAngle(
        Number(props.craneData.xAct),
        Number(props.craneData.yAct),
        Number(posx.value),
        Number(posy.value),
      );
    });

    // const mappingOrder = (lable: string) => {
    //   if (lable && orderTypeName) {
    //     return orderTypeName[lable];
    //   }
    // };

    const handleClick = (type: string) => {
      if (props.operateMode === '2') {
        return;
      }
      emitter.emit('inform', { name: 'terminal-crane-toolbar', value: type });
    };

    const orderTypeClick = (type: string) => {
      store.orderType = type;
    };

    const onModeChange = async () => {
      await api.post('CraneOperateModeChange', {
        craneNo: '01',
        operateMode: props.operateMode == '3' ? 2 : 3,
      });
    };

    // 此处使用 Vue3 中的组合式API
    // onMounted(() => {});

    const onShow = () => {
      console.log('sift.value', sift.value);
      // children: [
      //   {
      //     id: 'subTree1',
      //     children: [],
      //   },
      //   {
      //     id: 'subTree2',
      //     children: [],
      //   },
      // ];
      const data = {
        id: '全部',
        // label: '全部',
        children: sift.value.map(v => {
          const child: any = [];
          v.OrderType.split(',').forEach((b: any) => {
            child.push({ label: b, children: [] });
          });

          return {
            label: v.Group,
            children: child,
          };
        }),
      };

      if (container.value) {
        const graph = new G6.TreeGraph({
          container: container.value, // String | HTMLElement，必须，在 Step 1 中创建的容器 id 或容器本身
          width: 550, // Number，必须，图的宽度
          height: 350, // Number，必须，图的高度

          fitView: true,
          fitViewPadding: [20, 40, 50, 20],
          modes: {
            default: [
              {
                // 定义展开/收缩行为
                type: 'collapse-expand',
              },
              'drag-canvas',
            ],
          },

          layout: {
            type: 'Dendrogram', // 布局类型
            direction: 'LR', // 自左至右布局，可选的有 H / V / LR / RL / TB / BT
            nodeSep: 50, // 节点之间间距
            rankSep: 100, // 每个层级之间的间距
            excludeInvisibles: true, // 布局计算是否排除掉隐藏的节点，v4.8.8 起支持
            // size: 20,
          },
        });

        // 添加矩形元素
        // const group = graph.getGroup();
        // group.addShape('rect', {
        //   attrs: {
        //     fill: 'red',
        //     shadowOffsetX: 10,
        //     shadowOffsetY: 10,
        //     shadowColor: 'blue',
        //     shadowBlur: 10,
        //     opacity: 0.8,
        //   },
        //   name: 'rect-shape',
        // });
        // 读取数据
        graph.data(data);
        // 渲染图
        graph.render();

        graph.on('node:click', e => {
          // // 先将所有当前是 click 状态的节点置为非 click 状态
          // const clickNodes = graph.findAllByState('node', 'click');
          // clickNodes.forEach(cn => {
          //   graph.setItemState(cn, 'click', false);
          // });
          const nodeItem = e.item; // 获取被点击的节点元素对象
          // graph.setItemState(nodeItem, 'click', true); // 设置当前节点的 click 状态为 true
        });
      }
    };

    return {
      xDeviation,
      yDeviation,
      orderStatus,
      angle,
      handleClick,
      onModeChange,
      operateModeM,
      sift,
      orderTypeName,
      orderTypeClick,
      container,
      onShow,
    };
  },
});
</script>
<style lang="scss" scoped>
.crane {
  width: 38%;
  height: 110%;
  // border: 1px solid #dd9d4b;
  margin-top: -30px;
}

.craneInfo {
  width: 100%;
  height: 80%;
  // padding: 8px;
  background-image: url('assets/terminal-crane/info.png');
  background-repeat: no-repeat;
  background-size: 100% 100%;

  .ch1 {
    font-size: 18px;
    margin: 50px 0px 0px 30px;
  }

  .ch3 {
    font-size: 22px;
    font-weight: bold;
    margin-top: 60px;
    margin-left: 40px;
  }
}

.craneIocn {
  width: 100%;
  height: 20%;
  justify-content: space-between;

  .empty_is {
    width: 60px;
    height: 60px;
    position: relative;
    // border: 1px solid #000;
    background-image: url('assets/terminal-crane/isEmpty.png');
    background-repeat: no-repeat;
    background-size: 100% 100%;
    .child-element {
      position: absolute;
      bottom: -20px;
      left: 7px;

      width: 100%;
      height: 20px;
      color: #1c9158;
    }
  }

  .empty {
    width: 60px;
    height: 60px;
    position: relative;
    // border: 1px solid #000;
    background-image: url('assets/terminal-crane/empty.png');
    background-repeat: no-repeat;
    background-size: 100% 100%;
    .child-element {
      position: absolute;
      bottom: -20px;
      left: 7px;
      width: 100%;
      height: 20px;
      color: #1c9158;
    }
  }

  .network {
    width: 60px;
    height: 60px;
    position: relative;
    // border: 1px solid #000;
    background-image: url('assets/terminal-crane/networkNormal.svg');
    background-repeat: no-repeat;
    background-size: 100% 100%;
    .child-element {
      position: absolute;
      bottom: -20px;
      left: 0;
      width: 100%;
      height: 20px;
      color: #1c9158;
    }
  }

  .networkA {
    width: 60px;
    height: 60px;
    position: relative;
    // border: 1px solid #000;
    background-image: url('assets/terminal-crane/networkAbnormal.svg');
    background-repeat: no-repeat;
    background-size: 100% 100%;
    .child-element {
      position: absolute;
      bottom: -20px;
      left: 0;
      width: 100%;
      height: 20px;
      color: #8b0000;
    }
  }

  .lifting {
    width: 60px;
    height: 60px;
    position: relative;
    // border: 1px solid #000;
    background-image: url('assets/terminal-crane/forcedLifting.svg');
    background-repeat: no-repeat;
    background-size: 100% 100%;
    .child-element {
      position: absolute;
      bottom: -20px;
      left: 0;
      width: 100%;
      height: 20px;
      color: #1c9158;
    }
  }

  .lifting_2 {
    width: 60px;
    height: 60px;
    // border: 1px solid #000;
    position: relative;
    mask-image: url('assets/terminal-crane/forcedLifting.svg');
    background-color: #a9a9a9;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    .child-element {
      position: absolute;
      bottom: -20px;
      left: 0;
      width: 100%;
      height: 20px;
      color: #1c9158;
      z-index: 1;
    }
  }
  .unload {
    width: 60px;
    height: 60px;
    // border: 1px solid #000;
    position: relative;
    background-image: url(assets/terminal-crane/forcedRemoval.svg);
    background-repeat: no-repeat;
    background-size: 100% 100%;
    .child-element {
      position: absolute;
      bottom: -20px;
      left: 0;
      width: 100%;
      height: 20px;
      color: #1c9158;
    }
  }

  .unload_2 {
    width: 60px;
    height: 60px;
    position: relative;
    // border: 1px solid #000;

    // background-image: url(assets/terminal-crane/forcedRemoval.svg);
    mask-image: url('assets/terminal-crane/forcedRemoval.svg');
    background-color: #a9a9a9;
    background-repeat: no-repeat;
    background-size: 100% 100%;
    .child-element {
      position: absolute;
      bottom: -20px;
      left: 0;
      width: 100%;
      height: 20px;
      color: #000000;
    }
  }

  .sift {
    width: 60px;
    height: 60px;
    // border: 1px solid #000;
    background-image: url('assets/terminal-crane/sift.svg');
    background-repeat: no-repeat;
    background-size: 100% 100%;
    .child-element {
      position: absolute;
      bottom: -20px;
      left: 0;
      width: 100%;
      height: 20px;
      color: #1c9158;
    }
  }

  .setUp {
    width: 60px;
    height: 60px;
    // border: 1px solid #000;
    background-image: url('assets/terminal-crane/setUp.svg');
    background-repeat: no-repeat;
    background-size: 100% 100%;
  }
}

.example {
  padding: 5px;
  min-width: 165px;
  background-image: url('assets/terminal-crane/craneInfo_bg.png');
  background-repeat: no-repeat;
  background-size: 100% 100%;
  // border: 1px solid rgba(102, 102, 0, 0.5);
  // background-color: rgba(51, 51, 0, 0.5);
  .child-element {
    position: absolute;
    bottom: -20px;
    left: 0;
    width: 100%;
    height: 20px;
    color: #1c9158;
  }
}

.clock {
  width: 150px;
  height: 150px;
  // margin: 40px 0px 0px 80px;
  // background-color: #f2f2f2;
  border-radius: 50%;
  position: relative;
  border: 3px dashed #a7a3d6;
}

.hand {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 70px;
  height: 75px;
  // background-color: #000;
  // border: 1px solid #000;

  background-image: url('assets/terminal-crane/pointer.png');
  background-repeat: no-repeat;
  background-size: 100% 100%;
  transform-origin: bottom center;
  // border: 1px solid #a7a3d6;
}

.orderMenu {
  width: 550px;
  height: 350px;
  .left {
    height: 10%;
    width: 100%;
    .hexagon {
      width: 65px;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      text-align: center;
      border: 1px solid #a7a3d6;
    }
    .orderTpye {
      padding: 5px;
      border: 1px solid #a7a3d6;
    }
  }
}
</style>
